package com.sansan.qiangji.schedule;

import com.sansan.qiangji.entity.device.Stacker;
import com.sansan.qiangji.service.impl.device.StackerServiceImpl;
import com.sansan.qiangji.task.AsyncTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

@Component
@Slf4j
public class Schedule {
    private StackerServiceImpl stackerService;
    private AsyncTask asyncTask;

    @Resource
    public void setStackerService(StackerServiceImpl stackerService) {
        this.stackerService = stackerService;
    }

    @Resource
    public void setAsyncTask(AsyncTask asyncTask) {
        this.asyncTask = asyncTask;
    }

    @Scheduled(fixedDelay = 5000)
    public void updateStackerStatus() {
        List<Stacker> stackers = stackerService.findAllStacker();
        List<Future<Boolean>> futures = new ArrayList<>();
        for (Stacker stacker : stackers) {
            Future<Boolean> future = asyncTask.checkStackerStatus(stacker);
            futures.add(future);
        }
        while (true) {
            boolean isAllDone = true;
            for (Future<Boolean> future : futures) {
                if (!future.isDone()) {
                    isAllDone = false;
                }
            }
            if (isAllDone) {
                break;
            }
            try {
                Thread.sleep(500);
            }catch (Exception ignored){
            }
        }
    }
}
